<template>
  <div class="ck-warning">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" inline>
        <el-form-item label="货品">
          <el-input
            v-model="searchForm.goodsKeyword"
            placeholder="请输入货品名称/编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select
            v-model="searchForm.goodsType"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="饮品" value="饮品" />
            <el-option label="食品" value="食品" />
            <el-option label="电子产品" value="电子产品" />
            <el-option label="服装" value="服装" />
          </el-select>
        </el-form-item>
        <el-form-item label="上下限">
          <el-select
            v-model="searchForm.warningType"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="低于下限" value="below" />
            <el-option label="高于上限" value="above" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存">
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-input
              v-model="searchForm.currentStockMin"
              placeholder="请输入"
              type="number"
              style="width: 100px"
            />
            <span>~</span>
            <el-input
              v-model="searchForm.currentStockMax"
              placeholder="请输入"
              type="number"
              style="width: 100px"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="handleTestData" type="success">测试显示数据</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <!-- 调试信息 -->
      <div v-if="tableData.length === 0 && !loading" class="debug-info">
        <h3>调试信息</h3>
        <p>表格数据长度: {{ tableData.length }}</p>
        <p>分页总数: {{ pagination.total }}</p>
        <p>加载状态: {{ loading }}</p>
        <details>
          <summary>查看 tableData 内容</summary>
          <pre>{{ JSON.stringify(tableData, null, 2) }}</pre>
        </details>
      </div>
      
      <el-table 
        :data="tableData" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="expand" width="30">
          <template #default="{ row }">
            <div style="padding: 20px;">
              <p><strong>货品详情:</strong></p>
              <p>货品编号: {{ row.goodsCode }}</p>
              <p>货品名称: {{ row.goodsName }}</p>
              <p>规格型号: {{ row.specs }}</p>
              <p>单位: {{ row.unit }}</p>
              <p>货品类型: {{ row.goodsType }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="serialNumber" label="序号" width="80" align="center" />
        <el-table-column prop="goodsCode" label="货品编号" show-overflow-tooltip />
        <el-table-column prop="goodsName" label="货品名称" show-overflow-tooltip />
        <el-table-column prop="specs" label="规格型号" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="goodsType" label="货品类型" show-overflow-tooltip />
        <el-table-column prop="currentStock" label="当前库存" width="100" align="center" />
        <el-table-column prop="stockLowerLimit" label="库存下限" width="100" align="center" />
        <el-table-column prop="stockUpperLimit" label="库存上限" width="100" align="center" />
        <el-table-column prop="belowLowerLimitPercent" label="低于下限" width="100" align="center">
          <template #default="{ row }">
            <span :class="getPercentClass(row.belowLowerLimitPercent)">
              {{ row.belowLowerLimitPercent }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="aboveUpperLimitPercent" label="高于上限" width="100" align="center">
          <template #default="{ row }">
            <span :class="getPercentClass(row.aboveUpperLimitPercent)">
              {{ row.aboveUpperLimitPercent }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCkWarningPage, exportCkWarning, getCkWarningDetail } from '/@/api/ckWarning/ckWarning'

// 搜索表单
const searchForm = reactive({
  goodsKeyword: '',
  goodsType: '',
  warningType: '',
  currentStockMin: null as number | null,
  currentStockMax: null as number | null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 模拟数据
const mockData = [
  {
    id: '1900000000101',
    serialNumber: 1,
    goodsCode: 'HPDH1628',
    goodsName: '货品一',
    specs: '600ml 600毫升',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000102',
    serialNumber: 2,
    goodsCode: 'HPDH5401',
    goodsName: '货品二 产品2',
    specs: '红',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000103',
    serialNumber: 3,
    goodsCode: 'HPDH1629',
    goodsName: '货品三',
    specs: '90*20',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000104',
    serialNumber: 4,
    goodsCode: 'HPDH5402',
    goodsName: '货品四',
    specs: '蓝',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000105',
    serialNumber: 5,
    goodsCode: 'HPDH1630',
    goodsName: '货品五',
    specs: '1kg 1公斤',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000106',
    serialNumber: 6,
    goodsCode: 'HPDH5403',
    goodsName: '货品六',
    specs: '500ml',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000107',
    serialNumber: 7,
    goodsCode: 'HPDH1631',
    goodsName: '货品七',
    specs: '绿色',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000108',
    serialNumber: 8,
    goodsCode: 'HPDH5404',
    goodsName: '货品八',
    specs: '黄色',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000109',
    serialNumber: 9,
    goodsCode: 'HPDH1632',
    goodsName: '货品九',
    specs: '紫色',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  },
  {
    id: '1900000000110',
    serialNumber: 10,
    goodsCode: 'HPDH5405',
    goodsName: '货品十',
    specs: '橙色',
    unit: '件',
    goodsType: '饮品',
    currentStock: 50,
    stockLowerLimit: 10,
    stockUpperLimit: 100,
    belowLowerLimitPercent: 10.00,
    aboveUpperLimitPercent: 10.00
  }
]

// 获取百分比样式类
const getPercentClass = (percent: number) => {
  if (percent > 50) return 'percent-high'
  if (percent > 20) return 'percent-medium'
  return 'percent-low'
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    console.log('开始加载库存预警数据...')
    console.log('分页参数:', {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    
    // 调用真实的后端API
    const response = await getCkWarningPage({
      page: pagination.page,
      pageSize: pagination.pageSize,
      goodsKeyword: searchForm.goodsKeyword,
      goodsType: searchForm.goodsType,
      warningType: searchForm.warningType,
      currentStockMin: searchForm.currentStockMin,
      currentStockMax: searchForm.currentStockMax
    })
    
    console.log('API响应完整对象:', response)
    console.log('API响应类型:', typeof response)
    console.log('API响应数据结构:', Object.keys(response || {}))
    
    // 详细调试信息
    if (response) {
      console.log('response.data:', response.data)
      console.log('response.data类型:', typeof response.data)
      if (response.data) {
        console.log('response.data的键:', Object.keys(response.data))
        console.log('response.data.items:', response.data.items)
        console.log('response.data.total:', response.data.total)
        console.log('response.data.page:', response.data.page)
        console.log('response.data.pageSize:', response.data.pageSize)
      }
    }
    
    // 根据控制台观察，数据在 result.items 中
    let actualData = null
    
    if (response && response.data) {
      // response是完整的axios响应对象，数据在response.data中
      actualData = response.data
      console.log('从response.data中提取数据:', actualData)
    } else if (response && response.result) {
      // 数据可能在response.result中
      actualData = response.result
      console.log('从response.result中提取数据:', actualData)
    } else {
      // 没有data或result属性，直接使用response
      actualData = response
      console.log('直接使用response作为数据:', actualData)
    }
    
    // 处理实际数据 - 优先检查 result.items
    if (actualData && actualData.result && actualData.result.items) {
      // 数据在 result.items 中
      tableData.value = actualData.result.items
      pagination.total = actualData.result.total
      console.log('✅ 使用result.items结构 - 数据项数:', tableData.value.length, '总数:', pagination.total)
    } else if (actualData && actualData.items) {
      // SqlSugarPagedList结构 - 直接包含items和total
      tableData.value = actualData.items
      pagination.total = actualData.total
      console.log('✅ 使用SqlSugarPagedList结构 - 数据项数:', tableData.value.length, '总数:', pagination.total)
    } else if (Array.isArray(actualData)) {
      // 直接返回数组
      tableData.value = actualData
      pagination.total = actualData.length
      console.log('✅ 使用数组结构 - 数据项数:', tableData.value.length)
    } else if (actualData) {
      // 尝试其他可能的结构
      console.warn('⚠️ 未识别的数据结构:', actualData)
      console.log('actualData的键:', Object.keys(actualData))
      
      // 尝试强制提取数据
      if (actualData.data && actualData.data.items) {
        tableData.value = actualData.data.items
        pagination.total = actualData.data.total
        console.log('✅ 强制提取 actualData.data.items - 数据项数:', tableData.value.length)
      } else {
        tableData.value = []
        pagination.total = 0
      }
    } else {
      // 如果API调用失败，使用模拟数据作为降级方案
      console.warn('⚠️ API返回为空，使用模拟数据')
      tableData.value = mockData
      pagination.total = 100
    }
    
    console.log('最终设置结果:', {
      tableDataLength: tableData.value.length,
      paginationTotal: pagination.total,
      firstItem: tableData.value[0]
    })
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，使用模拟数据')
    // 使用模拟数据作为降级方案
    tableData.value = mockData
    pagination.total = 100
  } finally {
    loading.value = false
  }
}

// 测试显示数据
const handleTestData = () => {
  console.log('测试显示数据 - 设置模拟数据')
  tableData.value = mockData
  pagination.total = mockData.length
  console.log('测试数据设置完成:', {
    tableDataLength: tableData.value.length,
    paginationTotal: pagination.total,
    firstItem: tableData.value[0]
  })
}

// 刷新
const handleRefresh = () => {
  loadData()
}

// 导出
const handleExport = async () => {
  try {
    ElMessageBox.confirm('确定要导出库存预警信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const response = await exportCkWarning({
        page: pagination.page,
        pageSize: pagination.pageSize,
        ...searchForm
      })
      
      // 创建下载链接
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `库存预警信息_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('导出成功')
    })
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    goodsKeyword: '',
    goodsType: '',
    warningType: '',
    currentStockMin: null,
    currentStockMax: null
  })
  pagination.page = 1
  loadData()
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

// 组件挂载时加载数据
onMounted(() => {
  try {
    loadData()
  } catch (error) {
    console.error('组件挂载时加载数据失败:', error)
  }
})
</script>

<style scoped>
.ck-warning {
  padding: 20px;
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.debug-info {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.debug-info h3 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.debug-info p {
  margin: 5px 0;
  font-size: 14px;
}

.debug-info details {
  margin-top: 10px;
}

.debug-info pre {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  max-height: 200px;
}

/* 百分比样式 */
.percent-high {
  color: #f56c6c;
  font-weight: bold;
}

.percent-medium {
  color: #e6a23c;
  font-weight: bold;
}

.percent-low {
  color: #67c23a;
  font-weight: bold;
}
</style>

